package tink.macro;

/**
 * This class allows inline embeds.
 * The file path is relative to the embeding source file.
 * 
 * @example var x = Xml.parse(Embed.string('data.xml'));
 */
@:macro class Embed {
	/**
	 * Makes an inline embed of a string
	 * @param	file
	 */
	public static function string(file:String) {
		return new Impl().embedString(file);
	}
	/**
	 * Makes an inline embed of binary data
	 * @param	file
	 */
	public static function bytes(file:String) {
		return new Impl().embedBytes(file);
	}
}

#if macro
	import haxe.macro.Context;
	import neko.io.File;
	import haxe.macro.Expr;
	private class Impl extends Helper {
		public function new();
		public function embedString(file:String) {
			return embed(file, 'getString');
		}
		public function embedBytes(file:String) {
			return embed(file, 'getBytes');			
		}
		function embed(file:String, method:String) {
			var f = File.read(Context.resolvePath(file), true);
			var bytes = f.readAll();
			f.close();
			var id = Context.signature(bytes);
			Context.addResource(id, bytes);
			return 
				Magic.AST(haxe.Resource.eval__method(eval(string(id))));
		}
	}
#end